<template>
  <view class="video-player-page">
    <view class="video-container">
      <video 
        :src="videoUrl" 
        class="video-player"
        controls
        autoplay
        muted
        show-center-play-btn
        show-play-btn
        show-fullscreen-btn
        @error="onVideoError"
        @loadedmetadata="onVideoLoaded"
        @canplay="onVideoCanPlay"
        @play="onVideoPlay"
        @stalled="onVideoStalled"
        @waiting="onVideoWaiting"
        @progress="onVideoProgress"
      ></video>
    </view>
    <view class="download-tip">
      <text class="download-text">长按视频下载</text>
    </view>
    
    <view class="video-info">
      <text class="video-title"></text>
      <text class="video-desc">点击播放按钮开始观看</text>
    </view>
    
    <view class="action-buttons">
      <button class="action-btn back-btn" @click="goBack">返回</button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const videoUrl = ref('')
const candidates = ref([])
let candidateIndex = 0
let objectUrl = null

function buildCandidates(rawUrl) {
  const list = []
  // 原始地址
  list.push(rawUrl)
  // 无前导斜杠
  if (rawUrl.startsWith('/')) list.push(rawUrl.replace(/^\//, ''))
  // 绝对地址 - 基于 BASE_URL
  try {
    const base = (import.meta && import.meta.env && import.meta.env.BASE_URL) ? import.meta.env.BASE_URL : '/'
    const normalizedBase = base.endsWith('/') ? base.slice(0, -1) : base
    list.push(`${normalizedBase}${rawUrl}`)
  } catch (_) {}
  // 绝对地址 - 基于 origin
  try {
    if (typeof window !== 'undefined' && window.location && window.location.origin) {
      list.push(`${window.location.origin}${rawUrl}`)
    }
  } catch (_) {}
  // 去重
  const deduped = Array.from(new Set(list))
  return deduped
}

onMounted(() => {
  const pages = getCurrentPages()
  const current = pages[pages.length - 1]
  const { options } = current
  
  if (options.videoUrl) {
    const decoded = decodeURIComponent(options.videoUrl)
    console.log('加载视频原始地址:', decoded)
    // 针对本地 static 资源，准备多种写法兜底
    if (decoded.startsWith('/static/') || decoded.startsWith('static/')) {
      candidates.value = buildCandidates(decoded)
      candidateIndex = 0
      console.log('本地视频候选地址链:', candidates.value)
      prepareH5BlobSourceIfLocal(candidates.value[candidateIndex])
    } else {
      videoUrl.value = decoded
    }
    console.log('实际设置视频地址:', videoUrl.value)
  }
})

function tryNextCandidate() {
  if (!candidates.value.length) return false
  candidateIndex += 1
  if (candidateIndex < candidates.value.length) {
    const next = candidates.value[candidateIndex]
    console.warn('切换下一个本地视频候选地址:', next)
    prepareH5BlobSourceIfLocal(next)
    return true
  }
  return false
}

function onVideoError(e) {
  console.error('视频播放错误:', e)
  if (e && e.detail) console.error('视频错误明细 detail:', e.detail)
  // 若为本地 static 资源，依次尝试候选地址
  if (tryNextCandidate()) return
  // 网络视频播放失败，回退到备用视频
  if (videoUrl.value !== 'https://douyin-ai.tos-cn-shanghai.volces.com/06e0588c-a8ff-4add-a79b-d79a00af1a6e.mp4') {
    videoUrl.value = 'https://douyin-ai.tos-cn-shanghai.volces.com/06e0588c-a8ff-4add-a79b-d79a00af1a6e.mp4'
    return
  }
  uni.showToast({
    title: '视频播放失败',
    icon: 'none'
  })
}

function onVideoLoaded(e) {
  console.log('视频 loadedmetadata 事件:', { src: videoUrl.value, detail: e?.detail })
}
function onVideoCanPlay(e) {
  console.log('视频 canplay 事件:', { src: videoUrl.value, detail: e?.detail })
}
function onVideoPlay(e) {
  console.log('视频 play 事件:', { src: videoUrl.value, detail: e?.detail })
}
function onVideoStalled(e) {
  console.warn('视频 stalled 事件:', { src: videoUrl.value, detail: e?.detail })
}
function onVideoWaiting(e) {
  console.warn('视频 waiting 事件:', { src: videoUrl.value, detail: e?.detail })
}
function onVideoProgress(e) {
  console.log('视频 progress 事件:', { src: videoUrl.value, detail: e?.detail })
}

function prepareH5BlobSourceIfLocal(srcPath) {
  const isH5 = typeof window !== 'undefined' && !!window.document
  const isLocalStatic = srcPath?.startsWith('/static/') || srcPath?.startsWith('static/')
  if (isH5 && isLocalStatic) {
    // 通过 fetch 读取为 Blob，转为 blob URL，规避部分浏览器/路径问题
    fetch(srcPath)
      .then(async (res) => {
        if (!res.ok) throw new Error(`HTTP ${res.status}`)
        const blob = await res.blob()
        if (objectUrl) {
          try { URL.revokeObjectURL(objectUrl) } catch (_) {}
          objectUrl = null
        }
        objectUrl = URL.createObjectURL(blob)
        videoUrl.value = objectUrl
        console.log('使用 Blob URL 播放本地视频:', { from: srcPath, blobUrl: objectUrl })
      })
      .catch((err) => {
        console.error('读取本地视频为 Blob 失败:', err)
        videoUrl.value = srcPath
      })
  } else {
    videoUrl.value = srcPath
  }
}

function goBack() {
  uni.navigateBack()
}

</script>

<style lang="scss">
.video-player-page {
  min-height: 100vh;
  background: #1a1a1a;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.video-container {
  width: 100%;
  max-width: 400px;
  margin-bottom: 30px;
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(212, 175, 55, 0.2);
  aspect-ratio: 3 / 4;
  position: relative;
  background: #000;
}

.video-player {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  object-fit: contain;
  object-position: center center;
  border-radius: 20px;
  background: #000;
}

.video-info {
  text-align: center;
  margin-bottom: 30px;
}

.video-title {
  display: block;
  font-size: 24px;
  font-weight: 600;
  color: #ffffff;
  margin-bottom: 10px;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.video-desc {
  display: block;
  font-size: 16px;
  color: #a0826d;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.action-buttons {
  display: flex;
  gap: 20px;
  justify-content: center;
}

.action-btn {
  padding: 12px 24px;
  border-radius: 25px;
  border: none;
  font-size: 16px;
  font-weight: 600;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  transition: all 0.3s ease;
  
  &:active {
    transform: translateY(2px);
  }
}

.back-btn {
  background: linear-gradient(135deg, #a0826d, #8b4513);
  color: white;
}

.download-tip { text-align: center; margin-bottom: 12px; }
.download-text { font-size: 14px; font-weight: 600; color: #d4af37; letter-spacing: 1px; text-shadow: 0 1px 2px rgba(139,69,19,0.1); }
</style>
